package com.sky.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.SkyApplication;
import com.sky.entity.Employee;
import com.sky.vo.EmployeeVO;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.w3c.dom.Entity;

import java.io.IOException;

@SpringBootTest(classes = SkyApplication.class)
public class HttpClientDemo {

    @Test
    public void test01() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        CloseableHttpResponse response = httpClient.execute(httpGet);

        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("状态码:" + statusCode);

        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);

        System.out.println("返回的数据:" + body);

        response.close();
        httpClient.close();
    }

    @Test
    public void testPOST() throws Exception {
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建请求对象
        HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");

        //构造传递的json数据
        Employee employee = new Employee();
        employee.setUsername("admin");
        employee.setPassword("123456");
        String jsonStr = new ObjectMapper().writeValueAsString(employee);

        //将数据进行封装
        StringEntity entity = new StringEntity(jsonStr);
        entity.setContentEncoding("utf-8");
        entity.setContentType("application/json");

        //请求对象封装要发送的数据
        httpPost.setEntity(entity);

        // 发送请求，接受响应结果
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 获取服务端返回的状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("服务端返回的状态码为：" + statusCode);

        HttpEntity entity1 = response.getEntity();
        String body = EntityUtils.toString(entity1);
        System.out.println("服务端返回的数据为：" + body);

        // 关闭资源
        response.close();
        httpClient.close();
    }
}
